from flask import Blueprint, request, jsonify, redirect
import json
from db import db1
from .admin_user import get_data
from flask import current_app as app
from flask_mail import Mail, Message
from werkzeug.security import check_password_hash, generate_password_hash
import math
import requests

bp_user = Blueprint('user', __name__)


def send_email(title, email, content):
    mail = Mail(app)
    msg = Message(title, sender='ztlman12@163.com', recipients=[email])  # 发件人，收件人
    msg.html = content
    mail.send(msg)


@bp_user.route('/regi', methods=['POST'])
def regi():
    if request.method == 'POST':
        data = get_data()
        sql1 = '''select id from users where email = "%s" ''' % (data['email'])
        res = db1.findone(sql1)
        if res:
            return jsonify({'code': 20010, 'mes': 用户已存在})
        sql2 = '''insert into users values(0,"%s","%s",%d,"%s",%d)''' % (
            data['username'], generate_password_hash(data['password']), 0, data['email'], 0)
        print(sql2)
        db1.update(sql2)
        send_email('欢迎使用实验楼', data['email'],
                   "欢迎使用，点击以下<a href='http://localhost:5000/users/validEmail?email=" + data['email'] + "'>链接</a>验证")
        return jsonify({'code': 200})

@bp_user.route('/login',methods=['POST'])
def login():
    if request.method == 'POST':
        data = get_data()
        sql = 'select * from users where username = "%s"'%(data['username'])
        res = db1.findone(sql)
        if res:
            if check_password_hash(res['password'],data['password']):
                return jsonify({'code':200,'userid':res['id']})
            else:
                return jsonify({'code':20011,'mes':'密码错误'})
        else:
            return jsonify({'code':20012,'mes':'用户不存在'})

@bp_user.route('/validEmail')
def validEmail():
    email = request.args.get('email')
    sql = '''update users set status = 1 where email = "%s" ''' % (email)
    db1.update(sql)
    return redirect('http://localhost:8888')


@bp_user.route('/cates', methods=['GET'])
def cates():
    if request.method == 'GET':
        sal = 'select id,name from cates'
        res = db1.findall(sal)
        return jsonify({'code': 200, 'list': res})


@bp_user.route('/courese', methods=['GET'])
def courese():
    if request.method == 'GET':
        where = ' where 1 = 1'
        online = request.args.get('status')
        if online:
            where = where + ' and online = ' + str(online)

        status = request.args.get('course_type')
        if status:
            where = where + ' and status = ' + str(status)
        pid = request.args.get('course_tag')
        if pid:
            where = where + ' and pid = ' + str(pid)

        ordering = request.args.get('ordering')
        if ordering == '-create_time':
            where = where + ' and is_new = 1'
        elif ordering == '-learner':
            where = where + ' and is_host = 1'

        page = int(request.args.get('page'))
        page_size = int(request.args.get('page_size'))
        start = (page - 1) * page_size
        sql = 'select * from courses' + where + \
              ' limit %d,%d' % (start, page_size)
        print(sql)
        res = db1.findall(sql)
        sql1 = '''select count(id) from courses''' + where
        total = db1.findone(sql1)
        tpage = math.ceil(total['count(id)'] / page_size)
        return jsonify({'code': 200, 'list': res, 'total': tpage})


@bp_user.route('/weiboCallback/')
def weiboCallback():
    code = request.args.get('code')
    # 微博认证地址
    access_token_url = "https://api.weibo.com/oauth2/access_token"
    # 参数
    response = requests.post(access_token_url, data={
        "client_id": '3648830690',
        "client_secret": "916d80b477ccffce5d70e63b02bb1092",
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": "http://127.0.0.1:8000/users/weiboCallback/",
    })
    res = eval(str(response.text))
    print(res['uid'])
    print(res)
    try:
        uid = res['uid']
        print(uid)
        token = res['access_token']
        print(token)

    except:
        uid = 0

        return redirect('http://127.0.0.1:8888/')

        print(11111)

    sql = 'select u.id,u.username from sf_login as sf inner join users as u on sf.user_id = u.id where uid = %d' % (
        int(uid))
    res = db1.findone(sql)
    if res:
        return redirect('http://127.0.0.1:8000/users/bindmobile?type=1&id=' + res['id'] + '&username=' + res['username'])
    else:
        return redirect('http://127.0.0.1:8000/users/bindmobile?type=2&uid=' + uid + '&token=' + token)


@bp_user.route('/bindmobile', methods=['POST','GET'])
def bindmobile():
    if request.method == 'GET':
        # data = get_data()
        name = request.args.get('username')
        uid = request.args.get('uid')
        token = request.args.get('token')
        sql = 'select id from where username = "%s" ' % (name)
        res = db1.findone(sql)
        if res:
            return jsonify({'code': 10010, 'mes': '该用户已存在'})
        else:
            sql2 = 'insert into users(username,password,level,status) values ("%s","%s",%d,%d)' % (
                name, "123", 0, 1)
            db1.update(sql2)

            sql3 = 'select id from users where username = "%s" ' % (name)
            res3 = db1.findone(sql3)

            sql4 = 'insert into sf_login(user_id,platfrom,uid,token) values(%d,"weibo","%s","%s")' % (
                int(res3['id']), uid, token)
            db1.update(sql4)
            return jsonify({'code': 200, 'username': name, 'userid': res3['id']})

